<template>
    <div class="main">
        <!-- top -->
        <div class="top">
            <el-form :model="form" label-width="auto" style="max-width: 100%">
                <el-row>
                    <el-form-item label="课程名称">
                        <el-input v-model="form.name" placeholder="请输入课程名称" />
                    </el-form-item>
                    <el-form-item label="课程类型">
                        <el-select v-model="form.type" placeholder="课程类型">
                            <el-option label="舞蹈类" :value="1" />
                            <el-option label="游泳类" :value="2" />
                            <el-option label="拳击类" :value="3" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="适用人群">
                        <el-select v-model="form.applyTo" placeholder="适用人群">
                            <el-option label="中小学生" :value="1" />
                            <el-option label="上班族" :value="2" />
                            <el-option label="小白用户" :value="3" />
                            <el-option label="健身达人" :value="4" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="最低价格">
                        <el-input-number step="100" v-model="form.minPrice" :min="0" placeholder="最低价格" />
                    </el-form-item>
                    <el-form-item label="最高价格">
                        <el-input-number step="100" v-model="form.maxPrice" :min="0" placeholder="最高价格" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="search" :icon="Search">搜索</el-button>
                        <el-button :icon="Refresh">重置</el-button>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-button type="primary" :icon="Plus" @click="add" plain>新增</el-button>
                    <!-- :disabled="delId.length == 0":当delId的长度为0时禁用删除按钮 -->
                    <el-button type="success" :icon="Edit" plain :disabled="courseId.length !== 1"
                        @click="edit(null)">修改</el-button>
                    <el-button type="danger" :icon="Delete" plain :disabled="courseId.length == 0"
                        @click="del(null)">删除</el-button>
                    <el-button type="warning" :icon="Download" plain @click="exportXLsx">导出</el-button>
                </el-row>
            </el-form>
        </div>
        <!-- center -->
        <div>
            <!-- show-overflow-tooltip:当内容过长被隐藏时显示 tooltip -->
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="55" />
                <el-table-column property="courseId" label="课程编号" width="80" show-overflow-tooltip>
                </el-table-column>
                <el-table-column property="type" label="课程类型" width="120" show-overflow-tooltip>
                    <template #default="scope">
                        <el-tag type="primary" v-if="scope.row.type == 1">舞蹈类</el-tag>
                        <el-tag type="success" v-if="scope.row.type == 2">游泳类</el-tag>
                        <el-tag type="info" v-if="scope.row.type == 3">拳击类</el-tag>
                    </template>
                </el-table-column>
                <el-table-column property="name" label="课程名称" width="120" show-overflow-tooltip />
                <!-- show-overflow-tooltip -->
                <el-table-column property="price" label="课程价格" width="120" show-overflow-tooltip />
                <el-table-column property="applyTo" label="课程适用人群" show-overflow-tooltip width="150">
                    <template #default="scope">
                        <el-tag type="primary" v-if="scope.row.applyTo == 1">中小学生</el-tag>
                        <el-tag type="success" v-if="scope.row.applyTo == 2">上班族</el-tag>
                        <el-tag type="info" v-if="scope.row.applyTo == 3">小白用户</el-tag>
                        <el-tag type="warning" v-if="scope.row.applyTo == 4">健身达人</el-tag>
                    </template>
                </el-table-column>
                <el-table-column property="info" label="课程简介" width="180" show-overflow-tooltip />
                <el-table-column property="createTime" label="创建时间" width="180" show-overflow-tooltip />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type='primary' text='primary' :icon="Edit"
                            @click="edit(scope.row.courseId)">修改</el-button>
                        <el-button type='primary' text='primary' :icon="Delete"
                            @click="del(scope.row.courseId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- bottom -->
        <div class="demo-pagination-block">
            <el-pagination v-model:current-page="listParams.pageNum" v-model:page-size="listParams.pageSize"
                :page-sizes="[10, 20, 30, 40]" :size="size" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
        <!-- 新增&修改弹框 -->
        <div>
            <el-dialog v-model="dialogVisible" :title="title" width="500">
                <div>
                    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules"
                        label-width="auto">
                        <el-row class="elrow">
                            <el-form-item label="课程分类" prop="type">
                                <el-select v-model="ruleForm.type" placeholder="课程分类">
                                    <el-option label="舞蹈类" :value="1" />
                                    <el-option label="游泳类" :value="2" />
                                    <el-option label="拳击类" :value="3" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="课程名称" prop="name">
                                <el-input v-model="ruleForm.name" placeholder="请输入课程名称" />
                            </el-form-item>
                        </el-row>
                        <el-row class="elrow">
                            <el-form-item label="适用人群" prop="applyTo">
                                <el-select v-model="ruleForm.applyTo" placeholder="适用人群">
                                    <el-option label="中小学生" :value="1" />
                                    <el-option label="上班族" :value="2" />
                                    <el-option label="小白用户" :value="3" />
                                    <el-option label="健身达人" :value="4" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="课程价格" prop="price">
                                <el-input-number step="100" v-model="ruleForm.price" :min="0" placeholder="课程价格" />
                            </el-form-item>
                        </el-row>

                        <el-form-item label="课程简介" prop="info" placeholder="请输入内容">
                            <el-input v-model="ruleForm.info" type="textarea" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm(ruleFormRef)">
                                确定
                            </el-button>
                            <el-button @click="dialogVisible = false">取消</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-dialog>
        </div>
    </div>

</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, nextTick } from 'vue'
import { Search, Refresh, Plus, Download, Delete, Edit, Bottom } from '@element-plus/icons-vue'
import { courseList, courseSearch, courseAdd, courseEdit, courseDel, courseEdits, courseOut } from "@/api/course"
import type { ComponentSize, FormInstance, FormRules, TableInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'



// top**********************************
const form = reactive({
    pageNum: 1,
    pageSize: 10,
    name: '',
    type: '',
    minPrice: 'null',
    maxPrice: 'null',
    applyTo: '',
})
// 查询按钮
function searchList() {
    courseSearch(form).then(res => {
        console.log(res, "********************");
        tableData.value = res.rows
        total.value = res.total
    })
}
const search = () => {
    listParams.pageNum = 1
    searchList()
}
// 导出按钮
const exportXLsx = (() => {
    courseOut(form).then(res => {
        console.log(res, "导出成功");
        // 创建一个blob对象，存储excel文件的数据
        let blob = new Blob([res])
        // 创建一个a标签
        const link = document.createElement("a")
        // 创建一个下载链接，并将其赋值给href
        link.href = window.URL.createObjectURL(blob)
        link.target = "_blank"
        // 设置文件名
        let nowTime = new Date()
        link.setAttribute("download", `导出课程${nowTime.getTime()}.xlsx`)
        // 将a标签添加到页面上
        document.body.appendChild(link)
        // 触发点击事件
        link.click()
        // 移除a标签
        document.body.removeChild(link)
    })
        .catch(err => {
            console.log(err, "导出失败");
        })
})

// center***********************************************************
const tableData: any = ref([])

// 渲染页面
const listParams = reactive({
    pageNum: 1,
    pageSize: 10
})
const total = ref()
onMounted(() => {
    getList()
})
function getList() {
    courseList(listParams).then(res => {
        console.log(res, "********************");
        tableData.value = res.rows
        total.value = res.total
    })
}
// 修改按钮
const edit = ((val: any) => {
    if (val) {
        courseId.value = val
    }
    dialogVisible.value = true
    title.value = "修改课程"
    courseEdits(courseId.value).then(res => {
        console.log(courseId.value, "888888888");
        console.log(res, "555555");
        ruleForm.type = res.data.type
        ruleForm.name = res.data.name
        ruleForm.applyTo = res.data.applyTo
        ruleForm.price = res.data.price
        ruleForm.info = res.data.info
        courseId.value = res.data.courseId
        id.value = res.data.courseId
    })

})
// 删除按钮
const dialogVisibleDel = ref(false)
const del = ((val: any) => {
    let id = val ? val : courseId.value
    ElMessageBox.confirm(
        `是否确认删除课程编号为'${id}'的数据项`,
        '系统提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            courseDel(id).then(res => {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                dialogVisibleDel.value = false
                getList()
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除失败',
            })
        })
    // dialogVisibleDel.value = true
})
// 多选框
const selectable = (row: User) => ![1, 2].includes(row.id)
const handleSelectionChange = (val: any) => {
    courseId.value = []
    for (const item of val) {
        courseId.value.push(item.courseId)
    }
}

// Bottom**********************************************
const size = ref<ComponentSize>('default')
const background = ref(true)
const disabled = ref(false)
const handleSizeChange = (val: number) => {
    listParams.pageNum = 1
    listParams.pageSize = val
    getList()
}
const handleCurrentChange = (val: number) => {
    listParams.pageNum = val
    getList()
}
// 新增弹框*******************************
let title = ref('')
const dialogVisible = ref(false)
const add = (() => {
    dialogVisible.value = true
    title.value = "添加课程"
    // 重置表单
    nextTick(() => {
        ruleFormRef.value.resetFields()
    })
})
interface RuleForm {
    type: string
    name: string
    applyTo: string
    price: string
    info: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    type: '',
    name: '',
    applyTo: '',
    price: 'null',
    info: '',
})
const rules = reactive<FormRules<RuleForm>>({
    type: [
        { required: true, message: '课程类型不能为空', trigger: 'blur' },
    ],
    name: [
        { required: true, message: '课程名称不能为空', trigger: 'blur' },
    ],
    applyTo: [
        { required: true, message: '适用人群不能为空', trigger: 'blur' },
    ],
    price: [
        { required: true, message: '课程价格不能为空', trigger: 'blur' },
    ],
    info: [
        { required: true, message: '课程简介不能为空', trigger: 'blur' },
    ],
})
let courseId = ref([])
let id = ref([])
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value === "添加课程") {
                courseAdd(ruleForm).then(res => {
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    })
                    getList()
                    dialogVisible.value = false
                })
            } else {
                courseEdit({
                    courseId: id.value,
                    ...ruleForm
                }).then(res => {
                    console.log(res, "55555");
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    })
                    getList()

                    dialogVisible.value = false
                })
            }

        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>
<style lang="scss" scoped>
.main {
    padding: 20px;
}

:deep(.cell) {
    text-align: center;
}

// bottom***********
.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

.demo-pagination-block {
    display: flex;
    justify-content: right;
    padding: 30px 20px 20px;
}

.elrow {
    display: flex;
    flex-wrap: nowrap;
}

.el-form-item {
    margin-right: 20px;
}
</style>